#define _CRT_SECURE_NO_WARNINGS 1

#include "list.h"

ListNode* ListNewNode(LTDataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	assert(node);
	node->val = x;
	node->next = node->prev = NULL;
	return node;
}

ListNode* ListCreate()
{
	ListNode* head = ListNewNode(0);
	head->next = head->prev = head;
	return head;
}

void ListDestroy(ListNode** ppHead)
{
	assert(ppHead && *ppHead);
	ListNode* cur = (*ppHead)->next;
	while (cur!=*ppHead)
	{
		ListNode* tmp = cur->next;
		free(cur);
		cur = tmp;
	}
	free(*ppHead);
	*ppHead = NULL;
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* tmp = pHead->next;
	while (tmp != pHead)
	{
		printf("%d->", tmp->val);
		tmp = tmp->next;
	}
	printf("NULL\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* tail = pHead->prev;
	ListNode* newnode = ListNewNode(x);
	tail->next = newnode;
	newnode->prev = tail;
	pHead->prev = newnode;
	newnode->next = pHead;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(pHead != pHead->next);
	ListNode* tailprev = pHead->prev->prev;
	free(tailprev->next);
	tailprev->next = pHead;
	pHead->prev = tailprev;
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newnode = ListNewNode(x);
	newnode->next = pHead->next;
	pHead->next->prev = newnode;
	pHead->next = newnode;
	newnode->prev = pHead;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(pHead != pHead->next);
	ListNode* delnext = pHead->next->next;
	free(pHead->next);
	pHead->next = delnext;
	delnext->prev = pHead;
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	assert(pHead != pHead->next);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		if (cur->val == x)
		{
			return cur;
		}
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = ListNewNode(x);
	ListNode* prev = pos->prev;
	//prev newnode pos
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	//prev pos next
	free(pos);
	prev->next = next;
	next->prev = prev;
}